package cn.zqh.user.service.impl;


import cn.zqh.bean.api.CommonResult;
import cn.zqh.bean.api.ResultCode;
import cn.zqh.bean.bo.*;
import cn.zqh.user.client.RouterClient;
import cn.zqh.user.config.BSException;
import cn.zqh.user.holder.LoginUserHolder;
import cn.zqh.user.mapper.UserMapper;
import cn.zqh.user.mapper.UserPermissionConnectMapper;
import cn.zqh.user.service.UserService;
import cn.zqh.uuid.utils.SnowflakeId;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.xml.ws.handler.LogicalHandler;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zqh
 * @since 2022-12-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

//    @Autowired
//    private LoginUserHolder loginUserHolder;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserPermissionConnectServiceImpl userPermissionConnectServiceImpl;

    @Autowired
    private RouterClient routerClient;

    @Autowired
    private LoginUserHolder loginUserHolder;

    @Autowired
    private RestTemplate restTemplate;






    /**
      * @Author: zqh
      * @Date:
      * @Description: 注册一个新用户
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult createANewUser(String qq, String password,String Code) {
        //验证码校验
        CommonResult result = restTemplate.postForObject("http://127.0.0.1:9301/router/checkQQCode?email=" + qq + "&qQCode=" + Code, "", CommonResult.class);
//        CommonResult commonResult = routerClient.checkQQCode(qq, Code);
        if (result.getCode() != 200){
            return CommonResult.failed("验证码已失效或输入有误！");
        }
        if (qq == null || password == null) {
           throw new BSException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMessage());
        }

        User user = new User()
                .setUserId("user:" + SnowflakeId.nextId())
                .setNickName("新用户"+SnowflakeId.nextId())
                .setQqEmail(qq)
                .setPassword(passwordEncoder.encode(password))
                //性别默认为男
                .setSex(1)
                //头像默认基础头像，后面添加
                .setAvatar("http://sddklslkjsd")
                .setIntro("我是一名新用户")
                //地址默认为空
                .setAddress("**********")
                //是否拥有店铺
                .setIsStore(0)
                .setHavaMoney(0.0)
                .setIsDelete(0);
        int insert = userMapper.insert(user);
        if (insert != 1){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        //注册成功以后给其普通用户权限
        userPermissionConnectServiceImpl.permissionGranting(user.getUserId(),2);
        return CommonResult.success(ResultCode.SUCCESS);
    }
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 管理员修改用户信息
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult adminChangeInfo(AdminChangeUserInfo adminChangeUserInfo) {
        User GetUserByImail = userMapper.selectOne(new QueryWrapper<User>().eq("User_id", adminChangeUserInfo.getId()));
        //当更改邮箱时，看此邮箱在数据库中是否存在
        if (!GetUserByImail.getQqEmail().equals(adminChangeUserInfo.getEmail())){
            User email = userMapper.selectOne(new QueryWrapper<User>().eq("Qq_email", adminChangeUserInfo.getEmail()));
            if (email != null){
                return CommonResult.failed("该邮箱已经存在");
            }
        }
        User user = new User();
        user.setQqEmail(adminChangeUserInfo.getEmail())
                .setUserId(GetUserByImail.getUserId())
                .setNickName(adminChangeUserInfo.getName())
                .setSex(adminChangeUserInfo.getSex())
                .setAvatar(adminChangeUserInfo.getAvatar())
                .setIntro(adminChangeUserInfo.getIntro())
                .setAddress(adminChangeUserInfo.getAddress())
                .setIsStore(adminChangeUserInfo.getIsStore())
                .setHavaMoney(adminChangeUserInfo.getMoney())
                .setPassword(GetUserByImail.getPassword())
                .setIsDelete(adminChangeUserInfo.getIsDelete());
        int insert = userMapper.updateById(user);
        if (insert != 1){
            return CommonResult.failed();
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }
    
    /**
      * @Author: zqh
      * @Date: 
      * @Description: 更改密码
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult changePassword(String userId, String password) {
        User GetUserById = userMapper.selectOne(new QueryWrapper<User>().eq("User_id", userId));
        if (GetUserById == null){
          throw new BSException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage());
        }
        if (password == null || "".equals(password)){
            return CommonResult.failed("密码不符合规范");
            
        }
        String encode = passwordEncoder.encode(password);
        GetUserById.setPassword(encode);
        int i = userMapper.updateById(GetUserById);
        if (i != 1){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 用户修改自己信息
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult userCgOwnMation(UserChangeUserInfo userChangeUserInfo) {
        User GetUserByImail = userMapper.selectOne(new QueryWrapper<User>().eq("User_id", userChangeUserInfo.getId()));
        //当更改邮箱时，看此邮箱在数据库中是否存在
        if (!GetUserByImail.getQqEmail().equals(userChangeUserInfo.getEmail())){
            User email = userMapper.selectOne(new QueryWrapper<User>().eq("Qq_email", userChangeUserInfo.getEmail()));
            if (email != null){
                return CommonResult.failed("该邮箱已经存在");
            }
        }
        GetUserByImail.setQqEmail(userChangeUserInfo.getEmail())
                .setNickName(userChangeUserInfo.getName())
                .setSex(userChangeUserInfo.getSex())
                .setAvatar(userChangeUserInfo.getAvatar())
                .setIntro(userChangeUserInfo.getIntro())
                .setAddress(userChangeUserInfo.getAddress());

        int i = userMapper.insert(GetUserByImail);
        if (i != 1){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 通过用户id删除用户
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult delUserById(String userId) {
        int i = userMapper.deleteById(userId);
        if (i != 1){
            throw new BSException(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage());
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 查看已被禁用的账户
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getDelUser(Integer page, Integer size) {
        int x = (page - 1) * size;
        List<User> users = userMapper.getUsersByDelPage(x, size);
        return CommonResult.success(users);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 取消被删除了的用户
    */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public CommonResult cancelTheDeletedUser(String userId) {
        User user = userMapper.getDelUserBVyId(userId);
        if (user == null){
            throw new BSException(ResultCode.VALIDATE_FAILED.getCode(),ResultCode.VALIDATE_FAILED.getMessage());
        }
        userMapper.cancelDelUser(userId);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 分页查询未被删除的用户
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getAllUserByPage(Integer page, Integer size) {
        int x = (page - 1) * size;
        List<User> users = userMapper.getNoDelUser(x,size);
        return CommonResult.success(users);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 通过邮箱查询用户拥有的权限
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getUserPermission(String email) {
        List<String> list = userMapper.getRoleCodeByEmail(email);
        return CommonResult.success(list);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 查询登录用户信息
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getLoginUserInfo() {
        UserDTO currentUser = loginUserHolder.getCurrentUser();
        User user = userMapper.selectById(currentUser.getId());
        return CommonResult.success(user);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 通过id查询某个用户信息
    */
    @Override
    public CommonResult getuserById(String userId) {
        User user = userMapper.selectById(userId);
        if (user == null){
            return CommonResult.failed("用户不存在");
        }
        return CommonResult.success(user);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 获取所有用户的数量
    */
    @Override
    @Transactional(readOnly = true)
    public CommonResult getAllUserNumbers() {
       Integer title = userMapper.getAllUserNum();
        return CommonResult.success(title);
    }


    /**
      * @Author: zqh
      * @Date:
      * @Description: 管理员钱增加
    */
    @Override
    public CommonResult AdminUserAddMoney( Double money) {
        User user = userMapper.selectById("122211");
        user.setHavaMoney(user.getHavaMoney() + money);
        userMapper.updateById(user);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
      * @Author: zqh
      * @Date:
      * @Description: 某个用户钱减少
    */
    @Override
    public CommonResult userReMoney(String userId, Double money) {
        User user = userMapper.selectById(userId);
        Double v = user.getHavaMoney() - money;
        user.setHavaMoney(v);
        int i = userMapper.updateById(user);
        if (i != 1){
            return CommonResult.failed();
        }
        return CommonResult.success(ResultCode.SUCCESS);
    }
}
